package com.nus.servlets;

import com.nus.beans.Leave;
import com.nus.beans.User;
import com.nus.database.LeavesDBManager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/23/12
 * Time: 12:34 PM
 * To change this template use File | Settings | File Templates.
 */
public class VerifyLeavesServlet extends AbstractServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Enumeration e = request.getParameterNames();
        List<Leave> verifyLeaves = new ArrayList<Leave>();
        Leave tmpLeave;
        String errorMessage = null;
        boolean isVerifialble = true;
        String leaveInfo;

        Connection connection = getUserDatabaseConnection(request);
        LeavesDBManager leavesDBManager = new LeavesDBManager(connection);
        User user = (User) request.getSession().getAttribute("user");

        String[] leavesInfo;
        while(e.hasMoreElements()){
            leaveInfo = String.valueOf(e.nextElement());
            leavesInfo = leaveInfo.split("_");

            tmpLeave = new Leave(Integer.parseInt(leavesInfo[1]), new Date(Long.parseLong(leavesInfo[0])));
            verifyLeaves.add(tmpLeave);
        }

        //check leave status
        if(!verifyLeaves.isEmpty()){
        for(Leave leave: verifyLeaves){
            if(!leavesDBManager.isLeaveVerifiable(leave)){
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                errorMessage = "Leave on date " + formatter.format(leave.getDate()) + " is not cancelable";
                request.setAttribute("ERROR_MESSAGE", errorMessage);
                isVerifialble = false;
                break;
            } else {
                leave.setVerifiedBy(user.getUserId());
            }
        }

        if(isVerifialble){
            for(Leave leave : verifyLeaves){
                leavesDBManager.verifyLeave(leave);
            }
        }
        } else {
            errorMessage = "Please select some leave to verify.";
        }

        leavesDBManager.close();


        request.setAttribute("ERROR_MESSAGE", errorMessage);

        RequestDispatcher requestDispatcher = request.getRequestDispatcher("viewPendingLeaves.do");
        requestDispatcher.forward(request, response);
    }
}
